﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Linq;

namespace LiteQueryWPF.Entities
{
    public class Query
    {
        [XmlAttribute("rows")]
        public int Rows { get; set; } = 1;

        [XmlAttribute("columns")]
        public int Columns { get; set; } = 4;

        [XmlAttribute("heigth")]
        public int Heigth { get; set; } = 200;

        [XmlElement("Field")]
        public List<Field> Fields { get; set; } = new List<Field>();

        public string GetWhereSQL(bool existsWhere=true)
        {
            if (this.Fields == null || !this.Fields.Any())
                return string.Empty;

            var sb = new StringBuilder();
            if (!existsWhere)
                sb.Append(" where 1=1 ");

            foreach (Field item in this.Fields.Where(x=>!string.IsNullOrEmpty(x.Value)))
            {
                sb.Append(" and ");
                if (!string.IsNullOrEmpty(item.TableName))
                    sb.Append(item.TableName + ".");
                sb.Append(item.Name);
                sb.Append(" " + item.Operator + " ");
                if (item.Operator == "like")
                    sb.Append("'%" + item.Value + "%'");
                else
                {
                    if(item.ValueType=="text")
                        sb.Append("'" + item.Value + "'");
                    else
                        sb.Append( item.Value);
                }
            }

            return sb.ToString();
        }
    }
}
